package com.alnex.faceAi.service;


import javax.security.auth.Subject;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alnex.faceAi.base.FaceLoginResult;
import com.alnex.faceAi.base.QRCode;
import com.alnex.faceAi.base.User;
import com.alnex.faceAi.utils.BaiduAiUtil;
import com.alnex.faceAi.utils.IdWorker;
import com.alnex.faceAi.utils.QRCodeUtil;
import com.baidu.aip.util.Base64Util;

@Service
public class FaceLoginService {

    @Value("${qr.url}")
    private String url;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private QRCodeUtil qrCodeUtil;

    @Autowired
    private BaiduAiUtil baiduAiUtil;

	//创建二维码
    public QRCode getQRCode() throws Exception {
        String code = idWorker.nextId() + "";
        FaceLoginResult result = new FaceLoginResult("-1");
        redisTemplate.boundValueOps(getCacheKey(code)).set(result,30, TimeUnit.MINUTES);

        String strFile = qrCodeUtil.crateQRCode(url+"?code="+code);
        return new QRCode(code,strFile);
    }

	//根据唯一标识，查询用户是否登录成功
    public FaceLoginResult checkQRCode(String code) {
        return (FaceLoginResult) redisTemplate.opsForValue().get(getCacheKey(code));
    }

	//扫描二维码之后，使用拍摄照片进行登录
    public String loginByFace(String code, MultipartFile attachment) throws Exception {
        String userId = baiduAiUtil.faceSearch(Base64Util.encode(attachment.getBytes()));
        FaceLoginResult result = new FaceLoginResult("1");

        if (userId != null){
            //模拟查询数据库用户信息
            User user = new User("1001","模拟数据");
            //获取当前登录的用户信息  密码可能会加密
            // Subject subject = SecurityUtils.getSubject();
            // subject.login(new UsernamePasswordToken(user.getMobile(),user.getPassword()));
            // String token = subject.getSession().getId();
            // result = new FaceLoginResult("0", token, userId);
        }
        redisTemplate.boundValueOps(getCacheKey(code)).set(result,30,TimeUnit.MINUTES);

        return userId;
    }

	//构造缓存key
    private String getCacheKey(String code) {
        return "qrcode_" + code;
    }
}
